import gtk.glade
import gtk
import os
import os.path
import mode
import stats
from math import floor
from option import Option

def loadGlade(file):
	return gtk.glade.XML(os.path.join('data','glade',file))

def fmt(t):
	'''Transforms float to the human-readable format'''
	if t==-1.0:
		return '--:--'
	t=float(t)
	t=round(t,2)
	ret=[]
	if t > 3600:
		ret.append(str(int(t)/3600))

	if t > 60:
		ret.append(str(int(t)/60))
		t = t % 60.

	ret.append(str(t))
	return ':'.join(ret)

def unfmt(t):
	'''Transforms human-typed time to float form'''

	t = t.strip()
	
	if t == '--:--' or t == '-:--' or t == '--:-' or t == '-:-' or t == '--' or t == '-':
		return -1.

	if ',' in t:
		t = t.replace(',','.',1)
	
	if not ':' in t:
		return float(t)
	
	ret = 0.
	multiplicator = 1.
	for x in reversed(t.split(':')):
		ret += float(x) * multiplicator
		multiplicator *= 60.

	return ret
		
def ChangeMode(widget,m):
	if m!=Option().mode.options().name:
		Option().mode.teardown()
		Option().mode=mode.Mode(m)
		Option().windowMain.refresh()

	stats.refresh()

def log(txt):
	Option().windowMain.addLog(txt)

def message(txt, type = gtk.MESSAGE_INFO, buttons = gtk.BUTTONS_OK):
	dial = gtk.MessageDialog(message_format = txt, buttons = buttons, type = type)

	resp = dial.run()

	dial.hide()

	return resp

def on_resolution_changed(widget, type, period):
	cur = stats.CONN.cursor()

	period.get_model().clear()

	if type.get_active_text()  == _('Mode'):
		type_clause = 'WHERE mode_id = '+str(stats.getModeId())
	else:
		type_clause = ''
	
	DESCRIPTORS = {
			_('Daily') : "SELECT datetime(scores.created,'start of day') FROM scores %s GROUP BY datetime(scores.created,'start of day')" % type_clause,
			_('Monthly') : "SELECT datetime(scores.created,'start of month') FROM scores %s GROUP BY datetime(scores.created,'start of month')" % type_clause,
			_('Yearly') : "SELECT datetime(scores.created,'start of year') FROM scores %s GROUP BY datetime(scores.created,'start of year')" % type_clause,
			_('Global') : "SELECT * FROM scores WHERE score < 0.00",
			}
	BEAUTIFIERS = {
			_('Daily') : lambda x: x,
			_('Monthly') : lambda x: x[:x.rfind('-')],
			_('Yearly') : lambda x: x[:x.find('-')],
			_('Global') : lambda x: x,
			}

	for x in cur.execute(DESCRIPTORS[widget.get_active_text()]):
		period.append_text(BEAUTIFIERS[widget.get_active_text()](x[0].split()[0]))

	period.set_sensitive(False if widget.get_active_text() == _('Global') else True)
	period.set_active(0)


def on_type_changed(widget, period, resolution):
	if widget.get_active_text() == _('Session'):
		resolution.set_sensitive(False)
	else:
		resolution.set_sensitive(True)
	if widget.get_active_text() == _('Session') or resolution.get_active_text() == _('Global'):
		period.set_sensitive(False)
	else:
		period.set_sensitive(True)

def processPeriodSelection(type, resolution, period):
	
	# Type clause
	if type.get_active_text()  == _('Mode'):
		type_clause = 'mode_id = '+str(stats.getModeId())
	elif type.get_active_text() == _('Session'):
		return zip(Option().session.options().scores,xrange(1,len(Option().session.options().scores)+1))
	else:
		type_clause = False

	# Period clause
	if resolution.get_active_text() == _('Daily'):
		period_clause = "created >= datetime('%s','start of day') AND created <= datetime('%s','start of day','+1 day')" % (period.get_active_text(), period.get_active_text())
	elif resolution.get_active_text() == _('Monthly'):
		period_clause = "created >= datetime('%s-01','start of month') AND created <= datetime('%s-01','start of month','+1 month')" % (period.get_active_text(), period.get_active_text())
	elif resolution.get_active_text() == _('Yearly'):
		period_clause = "created >= datetime('%s-01-01','start of year') AND created <= datetime('%s-01-01','start of year','+1 year')" % (period.get_active_text(), period.get_active_text())
	else:
		period_clause = False


	where_clause = ['WHERE']
	type_clause and where_clause.append(type_clause)
	if period_clause:
		if len(where_clause) > 1:
			where_clause.append('AND')
		where_clause.append(period_clause)

	if len(where_clause) == 1:
		where_clause = []

	cur = stats.CONN.cursor()

	return cur.execute('SELECT score, created FROM scores '+' '.join(where_clause)).fetchall()


def createPeriodSelection():
	type = gtk.combo_box_new_text()
	type.append_text(_('Session'))
	type.append_text(_('Mode'))
	type.append_text(_('Global'))
	type.set_active(2)

	period = gtk.combo_box_new_text()

	resolution = gtk.combo_box_new_text()
	resolution.append_text(_('Daily'))
	resolution.append_text(_('Monthly'))
	resolution.append_text(_('Yearly'))
	resolution.append_text(_('Global'))
	resolution.set_active(3)

	type.connect('changed',on_type_changed, period, resolution)
	resolution.connect('changed',on_resolution_changed, type, period)
	return type, resolution, period


